package com.mall507.fivepeaks.activity.map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.google.gson.Gson;
import com.hzh.frame.ui.activity.BaseUI;
import com.hzh.frame.widget.rxbus.MsgEvent;
import com.hzh.frame.widget.rxbus.RxBus;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.activity.community.CommunityArtRFM;
import com.mall507.fivepeaks.activity.release.ReleaseFM;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.HashMap;
import java.util.List;

@Route(path = "/map/MapUI")
public class MapUI extends BaseUI{
    public static final String TAG="MapUI";
    public MapView mMapView;
    /**
     * 地图放大级别
     */
    private float mapZoom = 19;
    private BaiduMap mBaiduMap;
    private ProgressDialog mProgressDialog;
    /**
     * 地里编码
     */
    private GeoCoder mGeoCoder;
    /**
     * 是否是点击列表导致的移动
     */
    private boolean isRvClick = false;
    String addressName = "";
    String lat = "0.0";
    String lng = "0.0";
    String type = "";
    int mInt = 0;

    @Override
    protected void onCreateBase() {
        setContentView(R.layout.ui_rv_map);
        getTitleView().setContent("选择地址");
        getTitleView().setRightContent("确定");
        mMapView = findViewById(R.id.am_map);
        mBaiduMap = mMapView.getMap();
        mGeoCoder = GeoCoder.newInstance();
        initListener();
        getTitleView().setRightOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getIntent().getStringExtra("type") != null && getIntent().getStringExtra("type").length() > 0){
                    type = getIntent().getStringExtra("type");
                    if (type.equals("1")){
                        if (addressName != null && addressName.length() > 0){
                            onBackPressed();
                        }else {
                            alert("请选择地址");
                        }
                    }else if (type.equals("2")){
                        if (addressName != null && addressName.length() > 0){
                            ARouter.getInstance().build("/community/CommunityBusinessEnterUI")
                                    .withString("lat",lat)
                                    .withString("lng",lng)
                                    .withString("addressName",addressName)
                                    .withString("name",getIntent().getStringExtra("name"))
                                    .withString("phone",getIntent().getStringExtra("phone"))
                                    .withString("bussiness",getIntent().getStringExtra("bussiness"))
                                    .withString("classify",getIntent().getStringExtra("classify"))
                                    .withString("classifyTag",getIntent().getStringExtra("classifyTag"))
                                    .withString("area",getIntent().getStringExtra("area"))
                                    .withString("areaTag",getIntent().getStringExtra("areaTag"))
                                    .navigation();
                            finish();
                        }else {
                            alert("请选择地址");
                        }
                    }
                }
            }
        });
    }

    /**
     * 地图监听
     */
    private void initListener() {
        //地图加载完成回调
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                createSearch();
                requestPermission();
            }

        });
        //单击事件监听
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        //监听地图状态
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                if (!isRvClick) {
                    //得到中心点坐标，开始反地理编码
                    LatLng centerLatLng = mapStatus.target;
                    lat = String.valueOf(centerLatLng.latitude);
                    lng = String.valueOf(centerLatLng.longitude);
                    mInt = mInt + 1;
                    setEventBrowse(lat,lng,addressName);
                    mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(centerLatLng));
                }
            }
        });
        //监听地图的按下事件
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                //如果用户触碰了地图，那么把 isRvClick 还原
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    isRvClick = false;
                }
            }
        });
    }

    /**
     * 设置标记点的放大级别
     */
    private void setNewLatLngZoom(LatLng latLng) {
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latLng, mapZoom));
    }

    /**
     * 设置xy
     */
    private LatLng setLatLng(double lat, double lon) {
        return new LatLng(lat, lon);
    }

    /**
     * 定位用户位置用户位置
     */
    public void initUserLocation() {
        mProgressDialog = ProgressDialog.show(this, null, "正在定位,请稍后");
        //开启定位
        MapPositioning mapPositioning = new MapPositioning(this);
        mapPositioning.setmLocation(new MapPositioning.XbdLocation() {
            @Override
            public void locSuccess(BDLocation location) {
                mProgressDialog.dismiss();
                // 构造定位数据
                MyLocationData locData = new MyLocationData.Builder()
                        //设置精确度
                        .accuracy(0)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(0)
                        .latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();

                // 设置定位数据
                mBaiduMap.setMyLocationData(locData);
                // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
                BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_user_mark);
                //保存配置，定位图层显示方式，是否允许显示方向信息，用户自定义定位图标
                MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
                mBaiduMap.setMyLocationConfiguration(config);
                //移动到屏幕中心
                LatLng latLng = setLatLng(location.getLatitude(), location.getLongitude());
                setNewLatLngZoom(latLng);

                //设置用户地址
                PoiInfo userPoi = new PoiInfo();
                userPoi.location = latLng;

                userPoi.address = location.getAddrStr() + location.getLocationDescribe();
                userPoi.name = "[位置]";
                lat = String.valueOf(location.getLatitude());
                lng = String.valueOf(location.getLongitude());
                addressName = userPoi.address;
                mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            }

            @Override
            public void locFailure(int errorType, String errorString) {
                mProgressDialog.dismiss();
                alert(errorString);
            }
        });
        mapPositioning.start();
    }

    /**
     * 检索 创建
     */
    private void createSearch() {
        //兴趣点检索   没有用到
        PoiSearch poiSearch = PoiSearch.newInstance();
        OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult result) {
                //获取POI检索结果
                addressName = result.getAllPoi().get(0).address;
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult result) {
                //获取Place详情页检索结果
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
                //poi 室内检索结果回调
            }
        };
        poiSearch.setOnGetPoiSearchResultListener(poiListener);
        //地里编码
        mGeoCoder = GeoCoder.newInstance();
        OnGetGeoCoderResultListener getGeoListener = new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                }
                //设置搜索地址
                PoiInfo userPoi = new PoiInfo();
                userPoi.location = result.getLocation();
                userPoi.address = result.getSematicDescription();
                userPoi.name = "[位置]";

                //获取反向地理编码结果
                List<PoiInfo> poiList = result.getPoiList();
                if (poiList != null && poiList.size() > 0){
                    addressName = poiList.get(0).address;
                    setEventBrowse(lat,lng,addressName);
                }
            }
        };
        mGeoCoder.setOnGetGeoCodeResultListener(getGeoListener);
    }

    /**
     * 搜索返回后，需要先搜索
     */
    public void searchStr(String address, double lon, double lat) {
        if (lon > 0 && lat > 0) {
            LatLng latLng = setLatLng(lat, lon);
            //设置搜索地址
            PoiInfo userPoi = new PoiInfo();
            userPoi.location = latLng;
            userPoi.address = address;
            userPoi.name = "[位置]";
            addressName = userPoi.address;
            mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            setNewLatLngZoom(latLng);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppStaticVariable.MAP_SEARCH_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String address = data.getStringExtra(AppStaticVariable.MAP_SEARCH_ADDRESS);
                double lon = data.getDoubleExtra(AppStaticVariable.MAP_SEARCH_LONGITUDE, 0.0);
                double lat = data.getDoubleExtra(AppStaticVariable.MAP_SEARCH_LATITUDE, 0.0);
                searchStr(address, lon, lat);
            }
        }
    }

    /**
     * 获取权限，地图不需要权限，但是定位需要，建议在地图加载完成之后，再获取定位
     */
    private void requestPermission() {
        //扫码权限，文件权限
        AndPermission.with(this)
                .runtime()
                .permission(Permission.Group.LOCATION)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        initUserLocation();
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        alert("没有权限无法使用");
                    }
                }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    //更新浏览量
    private void setEventBrowse(String lat,String lng,String addressName){
        HashMap<String,Object> map = new HashMap<>();
        map.put("lat",lat);
        map.put("lng",lng);
        map.put("addressName",addressName);
        MsgEvent msgEvent=new MsgEvent(ReleaseFM.TAG,new Gson().toJson(map)); //发布
        RxBus.getInstance().post(msgEvent);
    }
    
}
